package com.zoe.app;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.date.TimeInterval;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;

/**
 * @author Zoe.Zhang
 * @date 2021/10/11
 * @description
 */
@Aspect
@Component
public class LogAspect {

    @Pointcut(value = "execution(* com.zoe.app.service.*.*(..))")
    public void joinPointCuts() {

    }

    @Around("joinPointCuts()")
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable {

        System.out.println("环绕通知---start");
        TimeInterval timer = DateUtil.timer();
        Object o;
        try {
            o = joinPoint.proceed();
            long l = timer.intervalSecond();
            System.out.println("环绕通知---end");
            System.out.println("方法执行耗费时间： " + l);
        } catch (Throwable throwable) {
            throwable.printStackTrace();
            long l = timer.intervalSecond();
            System.out.println("方法执行耗费时间： " + l);
            System.out.println("环绕通知异常---catch");
            // 环绕通知一定要把异常抛出去,否则全局异常拦截不到
            throw throwable;
        }
        return o;
    }

    @Before("joinPointCuts()")
    public void before(JoinPoint joinPoint) {
        final String name = joinPoint.getSignature().getName();
        System.out.println(name + "  方法运行前通知");
    }

    @After("joinPointCuts()")
    public void after(JoinPoint joinPoint) {
        final String name = joinPoint.getSignature().getName();
        System.out.println(name + "  方法运行后通知");
    }

    @AfterReturning(value = "joinPointCuts()", returning = "res")
    public void afterReturning(JoinPoint joinPoint, Object res) {
        final String name = joinPoint.getSignature().getName();
        System.out.println(name + "  方法返回后通知==>返回值:" + res);
    }

    @AfterThrowing(value = "joinPointCuts()", throwing = "e")
    public void afterThrowing(JoinPoint joinPoint, Exception e) {
        String name = joinPoint.getSignature().getName();
        System.out.println(name + " 方法异常通知: " + e.getMessage());
    }
}
